<template>
  <van-form>
    <van-cell-group inset>
      <van-field
        v-model="title"
        name="title"
        label="标题"
        placeholder="标题"
        :rules="[{ required: true, message: '请填写标题' }]"
      />
      <van-field
        v-model="body"
        name="body"
        label="内容"
        placeholder="内容"
        :rules="[{ required: true, message: '请填写内容' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" @click="updateMemo">
        更新
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';

import { toast } from '@/utils/toastHelper';
import { useLocalStorage } from '@vueuse/core';
import { useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const id = route.params.id;
const memoList = useLocalStorage('memo-list', []);

const currentMemoItem = computed(() => {
  return memoList.value.find((item) => Number(item.id) === Number(id));
});

const title = ref(currentMemoItem.value.title);
const body = ref(currentMemoItem.value.body);

function updateMemo() {
  memoList.value = memoList.value.map((memoItem) => {
    if (Number(memoItem.id) === Number(id)) {
      return {
        ...memoItem,
        title: title.value,
        body: body.value,
      };
    }

    return memoItem;
  });

  toast('成功更新');

  router.push('/memo');
}
</script>
